package com.eqxiu.ieditor.api.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eqxiu.bigdata.statistics.api.StatisticsApi2;
import com.eqxiu.ieditor.api.HomePageSceneServiceApi;
import com.eqxiu.ieditor.dao.HomePageUserMapper;
import com.eqxiu.ieditor.dao.HomePageUserSceneMapper;
import com.eqxiu.ieditor.dto.HomePageBaseInfoDTO;
import com.eqxiu.ieditor.dto.HomePageUserSceneDTO;
import com.eqxiu.ieditor.entity.HomePageUser;
import com.eqxiu.ieditor.entity.HomePageUserScene;
import com.eqxiu.ieditor.entity.HomePageUserSceneCriteria;
import com.eqxiu.mall.marketing.api.MarketComponentDictionaryApi;
import com.eqxiu.mall.marketing.dto.MarketComponentDictionaryDto;
import com.eqxiu.user.api.UserApi;
import com.eqxiu.user.api.dto.User;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName HomePageUserSceneServiceApiImpl
 * @escription TODO
 * @Author suixiangyu
 * @Date 2019/4/31:27 PM
 */
@Service
public class HomePageSceneServiceApiImpl implements HomePageSceneServiceApi {

    private final Logger LOGGER = LoggerFactory.getLogger(HomePageSceneServiceApiImpl.class);

    @Autowired
    private HomePageUserSceneMapper homePageUserSceneMapper;

    @Autowired
    private StatisticsApi2 statisticsApi2;

    @Resource
    private MarketComponentDictionaryApi cmptDictApi;

    @Resource
    private HomePageUserMapper homePageUserMapper;

    @Resource
    private UserApi userApi;

    @Override
    public void addHomePageScene(List<HomePageUserSceneDTO> homePageUserSceneDTOList) {
        List<HomePageUserScene> userSceneList = new ArrayList<>();
        for (HomePageUserSceneDTO homePageUserSceneDTO : homePageUserSceneDTOList) {
            HomePageUserScene homePageUserScene = new HomePageUserScene();
            BeanUtils.copyProperties(homePageUserSceneDTO, homePageUserScene);
            homePageUserScene.setCreateTime(new Date());
            homePageUserScene.setUpdateTime(new Date());
            userSceneList.add(homePageUserScene);
        }
        //从库中查询是否已经存在了，假如已经存在，则剔除
        if (CollectionUtils.isNotEmpty(userSceneList)) {
            Map<Integer, HomePageUserScene> userSceneMap = userSceneList.stream().collect(Collectors.toMap(HomePageUserScene::getSceneId, Function.identity(), (key1, key2) -> key2));
            List<Integer> homePageSceneIds = homePageUserSceneMapper.selectByUserIdAndSceneIds(userSceneList.get(0).getUserId(), Lists.newArrayList(userSceneMap.keySet()));
            LOGGER.info("homePageSceneIds" + JSON.toJSONString(homePageSceneIds));
            if (CollectionUtils.isNotEmpty(homePageSceneIds)) {
                List<HomePageUserScene> notExistSceneList = userSceneList.stream().filter(c -> !homePageSceneIds.contains(c.getSceneId())).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(notExistSceneList)) {
                    homePageUserSceneMapper.batchInsert(notExistSceneList);
                }
            } else {
                homePageUserSceneMapper.batchInsert(userSceneList);
            }
        }
    }

    @Override
    public void deleteHomePageScene(Integer sceneId) {
        HomePageUserSceneCriteria homePageUserSceneCriteria = new HomePageUserSceneCriteria();
        homePageUserSceneCriteria.createCriteria().andSceneIdEqualTo(sceneId);
        homePageUserSceneMapper.deleteByExample(homePageUserSceneCriteria);
    }

    @Override
    public void updateHomePageScene(HomePageUserSceneDTO homePageUserSceneDTO) {
        HomePageUserScene homePageUserScene = new HomePageUserScene();
        BeanUtils.copyProperties(homePageUserSceneDTO, homePageUserScene);
        HomePageUserSceneCriteria homePageUserSceneCriteria = new HomePageUserSceneCriteria();
        homePageUserSceneCriteria.createCriteria().andIdEqualTo(homePageUserSceneDTO.getId());
        homePageUserSceneMapper.updateByExampleSelective(homePageUserScene, homePageUserSceneCriteria);
    }

    @Override
    public Map<String, Object> queryHomePageByUserId(String userId, int pageNo, int pageSize, boolean orderByTime, boolean orderBySort) {
        HomePageUserSceneCriteria homePageUserSceneCriteria = new HomePageUserSceneCriteria();
        HomePageUserSceneCriteria.Criteria criteria = homePageUserSceneCriteria.createCriteria();
        if (orderByTime) {
            homePageUserSceneCriteria.setOrderByClause("create_time" + " " + "desc");
        }
        if (orderBySort) {
            homePageUserSceneCriteria.setOrderByClause("sort" + " " + "asc" + " ,create_time" + " " + "desc");
        }
        homePageUserSceneCriteria.setLimitStart((pageNo - 1) * pageSize);
        homePageUserSceneCriteria.setLimitEnd(pageSize);
        criteria.andUserIdEqualTo(userId);
        List<HomePageUserScene> homePageUserScenes = homePageUserSceneMapper.selectByExample(homePageUserSceneCriteria);
        int count = homePageUserSceneMapper.countByExample(homePageUserSceneCriteria);
        ArrayList<HomePageUserSceneDTO> homePageUserSceneDTOS = new ArrayList<>();
        for (HomePageUserScene homePageUserScene : homePageUserScenes) {
            HomePageUserSceneDTO homePageUserSceneDTO = new HomePageUserSceneDTO();
            try {
                Integer views = statisticsApi2.getPv(StatisticsApi2.PRODUCT_SCENE, homePageUserScene.getSceneId().toString());
                homePageUserSceneDTO.setPv(views);
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                homePageUserSceneDTO.setPv(0);
            }
            BeanUtils.copyProperties(homePageUserScene, homePageUserSceneDTO);
            homePageUserSceneDTOS.add(homePageUserSceneDTO);
        }
        Map<String, Object> map = Maps.newHashMap();
        map.put("total", count);
        map.put("rows", homePageUserSceneDTOS);
        return map;
    }

    @Override
    public int countHomePageBySceneId(Integer sceneId) {
        HomePageUserSceneCriteria homePageUserSceneCriteria = new HomePageUserSceneCriteria();
        homePageUserSceneCriteria.createCriteria().andSceneIdEqualTo(sceneId);
        List<HomePageUserScene> homePageUserScenes = homePageUserSceneMapper.selectByExample(homePageUserSceneCriteria);
        if (homePageUserScenes != null && homePageUserScenes.size() > 0) {
            return homePageUserScenes.size();
        } else {
            return 0;
        }
    }

    /**
     * @param userId
     * @param sceneIds
     * @Description 查询用户(userId)是否将该作品已经设置为微主页
     * @Author lifen
     * @Date 2019/9/18
     * @Param [userId, sceneIds]
     */
    @Override
    public Map<String, Object> isExistSceneByUserId(String userId, List<Integer> sceneIds) {
        List<Integer> homePageSceneIds = homePageUserSceneMapper.selectByUserIdAndSceneIds(userId, sceneIds);
        Map<String, Object> isExistSceneMap = new HashMap<>();
        sceneIds.forEach(s -> {
            if (homePageSceneIds.contains(Integer.valueOf(s.toString()))) {
                isExistSceneMap.put(s.toString(), true);
            } else {
                isExistSceneMap.put(s.toString(), false);
            }
        });
        return isExistSceneMap;
    }

    /**
     * @param userId
     * @param sceneIds
     * @Description 批量删除该用户的多个微主页作品
     * @Author lifen
     * @Date 2019/9/18
     * @Param [userId, sceneIds]
     */
    @Override
    public void batchRemoveHomePageScene(String userId, List<Integer> sceneIds) {
        homePageUserSceneMapper.batchDelete(userId, sceneIds);
    }

    @Override
    public HomePageBaseInfoDTO getHomePageBaseInfo(String sceneCode) {
        HomePageBaseInfoDTO homePageBaseInfoDTO = new HomePageBaseInfoDTO();
        // 用户基础信息
        HomePageUserScene homePageUserScene = homePageUserSceneMapper.getBySceneCode(sceneCode);
        if (null == homePageUserScene) {
            LOGGER.error("未查询到微主页用户-场景关联关系！");
            return null;
        }
        String userId = homePageUserScene.getUserId();
        HomePageUser homePageUser = homePageUserMapper.selectByPrimaryKey(userId);
        if (null == homePageUser) {
            LOGGER.error("未查询到微主页用户信息！");
            return null;
        }
        homePageBaseInfoDTO.setNickName(homePageUser.getNickName());
        homePageBaseInfoDTO.setSceneCode(sceneCode);

        // 用户头像
        User user = null;
        try {
            user = userApi.getUser(userId);
        } catch (Exception e) {
            LOGGER.error("根据userId查询用户失败！", e);
        }
        if (null != user) {
            homePageBaseInfoDTO.setPicLocation(user.getHeadImg());
        }

        // 组件信息
        List<MarketComponentDictionaryDto> cmptDictList = cmptDictApi.getCmptBySceneCode(sceneCode);
        if (CollectionUtils.isEmpty(cmptDictList)) {
            LOGGER.error("未查询到场景组件信息！");
            return null;
        }
        homePageBaseInfoDTO.setCmptDictDTOList(cmptDictList);
        return homePageBaseInfoDTO;
    }

    @Override
    public int isExistHomePage(String sceneCode,String userId) {
        return homePageUserSceneMapper.isExistHomePage(sceneCode,userId);
    }

}
